import { useAuthContext } from "../../context/AuthContext";
import useConversation from "../../store/useConversation";
import { formatTime } from "../../utils/formatTime";

const Message = ({ message }) => {
  const { authUser } = useAuthContext();
  const { selectedConveration } = useConversation();
  const fromMe = message.senderId === authUser._id;
  const chatClassName = fromMe ? "chat-end" : "chat-start";
  const profilePic = fromMe
    ? authUser.profilePic
    : selectedConveration.profilePic;
  const bubbleBgColor = fromMe ? "bg-blue-500" : "";
  const shakeClassName = message.shouldShake ? "shake" : "";

  return (
    <div className={`chat ${chatClassName}`}>
      <div className="chat-image avatar">
        <div className="w-10 rounded-full">
          <img
            alt={message?.fullName}
            src={profilePic}
            className="inline-block h-6 w-6 rounded-full ring-2 ring-white"
            onError={(img) => {
              img.target.src =
                "https://images.unsplash.com/photo-1491528323818-fdd1faba62cc?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=facearea&facepad=2&w=256&h=256&q=80";
            }}
          />
        </div>
      </div>
      <div
        className={`chat-bubble text-white pb-2 ${bubbleBgColor} ${shakeClassName}`}
      >
        {message.message}
      </div>
      <div className="chat-footer opacity-50 text-xs flex gap-1 items-center mt-1">
        {formatTime(message.createdAt)}
      </div>
    </div>
  );
};

export default Message;
